#!/usr/bin/python
#
# Copyright 2011 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""GIT session manager based on GaeSession

Defines the Git session manager based on GaeSession implementations.
"""

__author__ = 'Xin Zhou(zhounew@google.com)'

from git.session import git_session_manager_interface
from git.data import git_assertion, git_account
try:
  from gaesessions import get_current_session
except:
  pass

class GitGaeSessionBasedSessionManager(git_session_manager_interface.GitSessionManager):
  def __init__(self, git_config, git_account_service):
    self.git_config_ = git_config
    self.git_account_service_ = git_account_service

  def GetSessionAccount(self):
    session = get_current_session()
    if session.is_active():
      session_key = self.git_config_.Get('sessionUserKey')
      if session_key:
        accountJsonStr = session.get(session_key)
        return git_account.GitAccount.FromString(accountJsonStr)
    return None
  
  def SetSessionAccount(self, account):
    ''' account is the proto buffer for the RP's account information
    '''
    session = get_current_session()
    if session.is_active():
      session.terminate()
    session_key = self.git_config_.Get('sessionUserKey')
    if account:
      session[session_key] = account.ToJson()
      session.regenerate_id()
  
  def GetAssertion(self):
    session = get_current_session()
    if session.is_active():
      session_key = self.git_config_.Get('idpAssertionKey')
      if session_key:
        assertion_json_string = session.get(session_key)
        return git_assertion.GitAssertion.FromString(assertion_json_string)
    return None
  
  def SetAssertion(self, assertion):
    session = get_current_session()
    if session.is_active():
      session.terminate()
    session_key = self.git_config_.Get('idpAssertionKey')
    if assertion:
      session[session_key] = assertion.ToJsonString()
      session.regenerate_id()
    else:
      session.terminate()